package main

import (
	"changeme/zerr"
	"context"
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/wailsapp/wails/v2/pkg/runtime"
)

// App struct
type App struct {
	ctx context.Context
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{}
}

// startup is called at application startup
func (a *App) startup(ctx context.Context) {
	// Perform your setup here
	a.ctx = ctx
}

// domReady is called after front-end resources have been loaded
func (a App) domReady(ctx context.Context) {
	// Add your action here
}

// beforeClose is called when the application is about to quit,
// either by clicking the window close button or calling runtime.Quit.
// Returning true will cause the application to continue, false will continue shutdown as normal.
func (a *App) beforeClose(ctx context.Context) (prevent bool) {
	return false
}

// shutdown is called at application termination
func (a *App) shutdown(ctx context.Context) {
	// Perform your teardown here
}

// Greet returns a greeting for the given name
func (a *App) Greet(name string) string {
	return fmt.Sprintf("Hello %s, It's show time!", name)
}

func (a *App) Minmax() {
	runtime.WindowToggleMaximise(a.ctx)
}

func (a *App) Min() {
	runtime.WindowMinimise(a.ctx)
}

func (a *App) Quit() {
	runtime.Quit(a.ctx)
}
func (a *App) Reload() {
	runtime.WindowReloadApp(a.ctx)
	println("reload")
}

// update windows config
func (a *App) UpdateWindow(w string, h string) {
	window := map[string]string{
		"window-width":  w,
		"window-height": h,
	}
	e := DbPut(window)
	if e != zerr.SUCCESS {
		log.Println(zerr.GetMsg(e))
	}
	log.Println(zerr.GetMsg(e))
	fmt.Println(w, h)
}

// db get
func (a *App) DbGet(key string) string {
	data, err := DbGet(key)
	if err != zerr.SUCCESS {
		log.Println(zerr.GetMsg(err))
	}
	return data
}

func (a *App) HttpGet(url string) string {
	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Println(err)
	}

	req.Header.Set("User-Agent", "Golang_Spider_Bot/3.0")

	h, e := client.Do(req)
	if e != nil {
		//println("================err======================")
		log.Println(e)
	}
	body, e := io.ReadAll(h.Body)
	if e != nil {
		//println("================err======================")
		log.Println(e)
	}
	//println("======================================")
	//fmt.Printf("%s", body)

	return string(body)
}
